package com.zhouz.admin.app.jwt;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 维护用户token
 */
@Service
public class UserTokenService {
    //private ConcurrentLinkedQueue<String> refreshTokens = new ConcurrentLinkedQueue<>();
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Value("${token-active}")
    private String active;

    /**
     * 创建token
     * @Author 张鹏
     * @Date 2019-09-10 22:29
     * @param userCode
     * @return
     */
	public  String generateToken(String userCode) {
        JwtHelper jwtHelper = new JwtHelper();
        String token = jwtHelper.createToken(userCode,active);
        // 创建redis
        new Thread(()->{
            // 存储时间为 token的2倍
            redisTemplate.opsForValue().set(JwtHelper.REDIST_JWT+token,userCode,JwtHelper.expireHours*2, TimeUnit.HOURS);
        }).start();
        return token;
    }
    public String getUserId(String token) {
	    if(StringUtils.isBlank(token)){
	        return null;
        }
    	JwtHelper jwtHelper = new JwtHelper();
        String userId = jwtHelper.verifyTokenAndGetUserId(token,active);
    	if(StringUtils.isBlank(userId)){
    		return null;
    	}
    	// 方便下次用
        request.setAttribute(JwtHelper.LOGIN_TOKEN_KEY_CODE,userId);
    	// 刷新token时间 无需刷新
    	// this.refush(token);
        return userId;
    }

}
